var setting = {
    view: {
        selectedMulti: false,
		showLine: false
    },
    check: {
        enable: false
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    edit: {
        enable: false
    },
    callback: {
		onClick: loadMenu
	}
};

var zNodes = [];

function initTree(){
	$.post("/system/menu/findAllJson.do",{},function (data){
		var json = eval(data.result);
		zNodes = json;
		$.fn.zTree.init($("#tree"), setting, zNodes);
	});
}

function reset(){
	$("#validForm input[name='id']").val("");
    $("#validForm")[0].reset();
}

function btnClick(){
	$("#menuSave").click(function (){
		$("#validForm").submit();
	});
	$("#menuAdd").click(function (){
		reset();
	    var nodes = $.fn.zTree.getZTreeObj("tree").getSelectedNodes();
	    if(nodes.length > 0){
	    	 $("#validForm select[name='parent.id']").val(nodes[0].id);
	    }
	   /* for(var x in nodes[0]){
	    	console.info(x);
	    }*/
	});
	
	$("#menuDelete").click(function (){
		var nodes = $.fn.zTree.getZTreeObj("tree").getSelectedNodes();
	    if(nodes.length > 0){
	    	RM.confirm("确认删除该菜单?",function (){
	    		var ids = new Array();
	    		for(var i = 0 ; i < nodes.length ; i ++){
	    			ids.push(nodes[i].id);
	    		}
				RM.ajax("/system/menu/dels.do",{"ids":ids},function (data){
					RM.alert(data.message);
					if(data.code == 0){
						initTree();
					}
				});
			});
	    }else{
	    	RM.msg("请选择菜单!");
	    }
	});
}

function validata(){
	$("#validForm").validate({
	 	submitHandler: function() {
	 		var params = $("#validForm").serialize();
			RM.ajax("/system/menu/save.do", params,function(data){
				RM.alert(data.message);
				if(data.code == 0){
					initTree();
				}
			});
		}
	});
}

function loadMenu(event, treeId, treeNode) {
    var menuId = treeNode.id;
    var parentId = treeNode.pId;
    var menuName = treeNode.name;
    var menuUrl = treeNode.menuUrl;
    var menuSort = treeNode.menuSort;
    var permission = treeNode.permission;
    var menuIcon = treeNode.menuIcon;
    $("#validForm input[name='id']").val(menuId);
    $("#validForm input[name='name']").val(menuName);
    $("#validForm input[name='url']").val(menuUrl);
    $("#validForm input[name='permission']").val(permission);
    $("#validForm input[name='sort']").val(menuSort);
    $("#validForm select[name='parent.id']").val(parentId);
    $("#validForm select[name='icon']").val(menuIcon);
};

$(function (){
	initTree();
	btnClick();
	validata();
});
